import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pylab import mpl

# 设置中文字体
mpl.rcParams['font.sans-serif'] = ['SimHei']
# 设置正常显示符号
mpl.rcParams['axes.unicode_minus'] = False

# 需求：
# 1.评分的平均分
# 2.导演的总数目
# 3.rating的分布情况
# 4.genre的数量占比
movies = pd.read_csv("IMDB-Movie-Data.csv")

# 1.评分的平均分
Metascore_mean = movies["Metascore"].mean(0)
print(Metascore_mean)

# 2.导演的总数目
Director_num = movies["Director"].unique().shape[0]
print(type(movies["Director"].unique()))  # <class 'numpy.ndarray'>

print(Director_num)

# # 3.rating的分布情况
# Rating_min = movies["Rating"].min(0)
# Rating_max = movies["Rating"].max(0)
# ratings = movies["Rating"].values
# print(ratings)
# plt.figure(figsize=(15, 8), dpi=80)
# plt.hist(ratings, bins=20)
# plt.xticks(np.linspace(Rating_min, Rating_max, 21))
# plt.grid(True)
# plt.title("电影rating的分布情况")
# plt.show()

# 4.genre的数量占比
genres = movies["Genre"]
temp_list = [j.split(",") for j in genres.values]
genres = [i for j in temp_list for i in j]

genres_list = np.unique(genres)
df = pd.DataFrame(np.zeros([movies["Genre"].shape[0], genres_list.shape[0]]), columns=genres_list)
print(df.head())
"""
     Action  Adventure  Animation  Biography  ...  Sport  Thriller  War  Western
0       0.0        0.0        0.0        0.0  ...    0.0       0.0  0.0      0.0
1       0.0        0.0        0.0        0.0  ...    0.0       0.0  0.0      0.0
2       0.0        0.0        0.0        0.0  ...    0.0       0.0  0.0      0.0
3       0.0        0.0        0.0        0.0  ...    0.0       0.0  0.0      0.0
4       0.0        0.0        0.0        0.0  ...    0.0       0.0  0.0      0.0
"""
for i in range(movies["Genre"].shape[0]):
    df.iloc[i, df.columns.get_indexer(temp_list[i])] = 1
print(df.head())
"""
   Action  Adventure  Animation  Biography  ...  Sport  Thriller  War  Western
0     1.0        1.0        0.0        0.0  ...    0.0       0.0  0.0      0.0
1     0.0        1.0        0.0        0.0  ...    0.0       0.0  0.0      0.0
2     0.0        0.0        0.0        0.0  ...    0.0       1.0  0.0      0.0
3     0.0        0.0        1.0        0.0  ...    0.0       0.0  0.0      0.0
4     1.0        1.0        0.0        0.0  ...    0.0       0.0  0.0      0.0
"""
genres_sum = df.sum(0).sort_values(ascending=True)
print(genres_sum)
print(genres_sum.index)
"""
Musical        5.0
Western        7.0
War           13.0
Music         16.0
Sport         18.0
History       29.0
Animation     49.0
Family        51.0
Biography     81.0
Fantasy      101.0
Mystery      106.0
Horror       119.0
Sci-Fi       120.0
Romance      141.0
Crime        150.0
Thriller     195.0
Adventure    259.0
Comedy       279.0
Action       303.0
Drama        513.0
"""
plt.figure(figsize=(15, 8), dpi=80)
plt.bar(range(genres_sum.shape[0]), genres_sum.values, width=0.5)
plt.xticks(range(genres_sum.shape[0]),genres_sum.index)
plt.xlabel("电影分类")
plt.ylabel("数量")
plt.grid(True)
plt.show()
